<template>
  <view class="files-box">
    <!-- 附件 -->
    <uni-swipe-action>
      <template v-for="(item, index) in info.files" :key="item.fileno">
        <uni-swipe-action-item
          :disabled="props.disabled"
          :right-options="info.options2"
          @click="fileClick(item, $event)"
        >
          <view class="files-item" @click="goToDownFn(item)">
            <view class="files-left">
              <FileIcon :filename="item.filename" :size="50" />
            </view>
            <view class="files-right">
              <view class="files-name">{{ item.filename || '-' }}</view>
            </view>
          </view>
        </uni-swipe-action-item>
      </template>
    </uni-swipe-action>

    <!-- webview 环境 -->
    <AudioPlayerWidthWebview
      v-if="info.environmentType === 'window_plus_has'"
      ref="audioPlayer"
    />
    <!-- h5环境 -->
    <!-- <AudioH5 v-else-if="getEnvironmentType === 'window_plus_no'" ref="audioPlayer" /> -->
    <!-- app环境 -->
    <AudioPlayerWidthApp
      v-if="info.environmentType === 'app_plus'"
      ref="audioPlayer"
    />
  </view>
</template>

<script setup>
import { onMounted } from 'vue';
import utils from '@/common/js/utils/index.js';
const Custom_sendLog = utils.Custom_sendLog; // 输出日志
const audioPlayer = ref(null);

const props = defineProps({
  files: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: () => false,
  },
});

const emit = defineEmits(['update:modelValue']);

const info = reactive({
  environmentType: '', // 运行环境
  files: [],
  options2: [
    {
      text: '删除',
      style: {
        backgroundColor: '#ff0000',
      },
    },
  ],
});
onMounted(() => {
  info.environmentType = utils.getEnvironmentType();
});

function getBaseUrl() {
  const baseUrl = uni.getStorageSync('serverUrl');
  if (!baseUrl) {
    uni.showToast({
      title: '未配置服务器地址',
      icon: 'none',
      duration: 2000,
    });
    return null;
  }
  return baseUrl;
}

const goToDownFn = (item) => {
  /*
  {
    "createtime": "2024-12-24 14:28:18",
    "filename": "1735008633623.mp4",
    "fileno": "1735009587386",
    "source": "DESKTOP",
    "createuser": "800180",
    "class": "class com.eam.order.pojo.EamMrFile",
    "seq": "1735021698841",
    "mrSeq": "1735007179207"
  }

  {
    "createtime": "2025-02-07 15:52:11",
    "filename": "IMG_20250113_160028.jpg",
    "fileno": "1738914722774",
    "mr_seq": "1738913752379",
    "source": "MOBILE",
    "createuser": "Administrator",
    "seq": "1738914731348"
  }
  */
  console.log('down-item', item);
  console.log(110, item.source === 'MOBILE');
  if (item.source === 'MOBILE') {
    const pre_url = getBaseUrl();
    if (!item.filename || !item.filename.includes('.')) {
      uni.showToast({
        title: '类型暂不可预览',
        icon: 'none',
      });
      return false;
    }
    const fileType = item.filename.split('.').pop().toLowerCase();

    const type_1 = ['jpg', 'jpeg', 'png', 'gif']; // 图像
    const type_2 = ['mp3', 'wav', 'ogg', 'amr', 'aac', '3gp']; // 录音
    const type_3 = ['mp4', 'avi', 'mov', 'wmv']; // 视频

    const flag_1 = type_1.includes(fileType);
    const flag_2 = type_2.includes(fileType);
    const flag_3 = type_3.includes(fileType);

    const isOthrer = !flag_1 && !flag_2 && !flag_3;
    if (isOthrer) {
      uni.showToast({
        title: '类型暂不可预览',
        icon: 'none',
      });
      return false;
    }

    uni.downloadFile({
      url:
        pre_url +
        '/eis.gridfileload?service=appuService&method=download&flag=upload&appuseq=' +
        item.fileno,
      success: (downloadRes) => {
        if (downloadRes.statusCode === 200) {
          const tempFilePath = downloadRes.tempFilePath;
          if (flag_1) {
            uni.previewImage({
              urls: [tempFilePath],
            });
          } else if (flag_2) {
            audioPlayer.value.open(tempFilePath);
          } else if (flag_3) {
            uni.navigateTo({
              url: `/pages/only/videoPlayer?src=${encodeURIComponent(
                tempFilePath
              )}`, // 传递视频源
            });
          } else {
            console.log('非三界文件');
            uni.showToast({
              title: '此文件无法预览',
              icon: 'none',
            });
          }
        } else {
          console.error('文件下载出错:', downloadRes);
          uni.showToast({
            title: '文件下载出错，请重试',
            icon: 'none',
          });
        }
      },
      fail: (error) => {
        console.error('下载请求失败:', error);
        uni.showToast({
          title: '文件下载失败，请重试',
          icon: 'none',
        });
      },
    });
  } else {
    uni.showToast({
      title: '只能预览移动端上传的文件',
      icon: 'none',
    });
  }
};

const showDeleteConfirmation = (id) => {
  uni.showModal({
    title: '确认删除',
    content: '是否确定要删除这个附件？',
    success: function (res) {
      if (res.confirm) {
        info.files = info.files.filter((item) => item.fileno !== id);
        console.log('删除后的', info.files);
        emit('update:modelValue', info.files);
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};

const fileClick = (item, e) => {
  if (e.content.text === '删除') {
    showDeleteConfirmation(item.fileno);
  } else {
    uni.showToast({
      title: `点击了${e.content.text}按钮`,
      icon: 'none',
    });
  }
};

// watch(
//   () => props.files,
//   (newVal) => {
//     info.files = newVal;
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// );

watchEffect(() => {
  info.files = props.files;

  // 临时模拟数据
  // info.files = [
  //   {
  //     filename: 'twitter.svg',
  //     fileno: '1725179202243',
  //   },
  //   {
  //     filename:
  //       '1725420114289_Screenshot_2023-05-06-09-18-27-509_plus.H53A70341.png',
  //     fileno: '1725179202243',
  //   },
  //   {
  //     filename:
  //       '1725420114289_Screenshot_2023-05-06-09-18-27-509_plus1725420114289_Screenshot_2023-05-06-09-18-27-509_plus.H53A70341.png',
  //     fileno: '1725179202243',
  //   },
  // ];
});
</script>

<style lang="scss" scoped>
.files-box {
  background-color: #fff;

  .files-item {
    display: flex;
    align-items: flex-start;
    padding: 10rpx;
    flex-wrap: wrap;
    align-items: center;

    .files-left {
      width: 80rpx;
      min-height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .files-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .files-right {
      width: calc(100% - 80rpx);
      max-width: calc(100% - 80rpx);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: 0 15rpx 0 10rpx;
      word-wrap: break-word;
      /* 添加这行实现文字自动换行 */

      .files-name {
        color: #666;
        font-size: 22rpx;
        line-height: 24rpx;
      }
    }
  }
}
</style>
